﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KL.Store.Data;
using KL.Store.Core;
using KL.Store.Core.Domain;
using KL.Store.Web.Models;

namespace KL.Store.Web.Controllers
{
    public class SearchController : KL.Store.Core.Web.BaseController
    {
        #region Index

        public ActionResult Index(string search)
        {
            ViewBag.Controller = "search_crtl";

            SearchModel sm = new SearchModel();
            ViewBag.Title = "Ara";
            if (string.IsNullOrEmpty(search)) search = "";
            sm.Search = search;

            sm.BreadCrumb = "";

            if (!string.IsNullOrEmpty(search))
            {
                ViewBag.Keywords = search;
                ViewBag.Description = search;
                sm.Search = search;
            }
            eStoreUser.RedirectUrl = "/Search/Index?Search=" + search;
            return View(sm);
        }

        #endregion

        #region LiveSearch

        [HttpPost]
        public ActionResult LiveSearch(string search)
        {
            IList<ProductLiveSearch> searchmodel;
            searchmodel = dbProduct.GetLiveSearch(search);

            return Json(new { LiveSearch = searchmodel, ProductCount = searchmodel.Count() }, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region LiveSearchFull

        [HttpPost]
        public ActionResult LiveSearchFull(string search)
        {
            IList<ProductLiveSearch> searchmodel;
            searchmodel = dbProduct.GetLiveSearchFull(search);

            return Json(new { LiveSearch = searchmodel, ProductCount = searchmodel.Count() }, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region Get

        [Child]
        public ActionResult Get(int? id, int? brand, int? sort, int? order, int? itemCount, decimal? minPrice, decimal? maxPrice, string search, int page = 1)
        {
            if (!string.IsNullOrEmpty(search)) search = HttpUtility.UrlDecode(search);
            if (search.Length < 2) return Content("<div class=\"col-xs-12 col-sm-12 col-md-9 col-lg-10 right\"><div class=\"bg-info bs-bgb\" style=\"margin-bottom: 15px; color: #000000;\"><span class=\"glyphicon glyphicon-info-sign\"></span>&nbsp;Arama kriteri giriniz.</div></div>");
            ProductsModel productsModel = new ProductsModel();
            productsModel.BasketLocked = eStoreUser.BasketLocked;
            productsModel.Sort = 1;
            productsModel.Order = 1;
            int PageStart = (page * (int)itemCount) - (int)itemCount;
            int PageEnd = (int)itemCount;
            ViewBag.Page = page;
            productsModel.IsManager = eStoreUser.IsManager;
            productsModel.IsSeoManager = eStoreUser.IsSeoManager;

            if (!id.HasValue)
            {
                id = 0;
            }

            if (!brand.HasValue) brand = 0;
            if (string.IsNullOrEmpty(search)) search = "";
            if (!sort.HasValue) sort = 1;
            if (!order.HasValue) order = 1;

            productsModel.Sort = (int)sort;
            productsModel.Order = (int)order;
            productsModel.Brand = (int)brand;
            productsModel.SearchText = search;

            var posListe = dbPos.GetList().Where(o => o.PosVoucher == "S").FirstOrDefault();
            if (posListe != null)
            {
                posListe.PosInstallment = dbPos.GetInstallmentList(posListe.PosId, 1, 9999, 0, 0);
                productsModel.VoucherRate = posListe.PosInstallment != null ? posListe.PosInstallment.Where(o => o.InstallmentNumber == Parameters.SenetTaksit1).FirstOrDefault().CommissionRate : (1 + (Parameters.SenetEkUcret / 100));
            }
            if (productsModel.Sort == 1)
            {
                if (productsModel.Order > 1)
                {
                    productsModel.RelatedProducts = dbProduct.GetList((int)id, 0, (int)brand, eStoreUser.AccountId, search).OrderByDescending(o => o.ProductName).ToArray<Product>();
                }
                else
                {
                    productsModel.RelatedProducts = dbProduct.GetList((int)id, 0, (int)brand, eStoreUser.AccountId, search).OrderBy(o => o.ProductName).ToArray<Product>();
                }
            }
            else if (productsModel.Sort == 2)
            {
                if (productsModel.Order > 1)
                {
                    productsModel.RelatedProducts = dbProduct.GetList((int)id, 0, (int)brand, eStoreUser.AccountId, search).OrderByDescending(o => o.SpecialPrice).ToArray<Product>();
                }
                else
                {
                    productsModel.RelatedProducts = dbProduct.GetList((int)id, 0, (int)brand, eStoreUser.AccountId, search).OrderBy(o => o.SpecialPrice).ToArray<Product>();
                }
            }
            else if (productsModel.Sort == 3)
            {
                if (productsModel.Order > 1)
                {
                    productsModel.RelatedProducts = dbProduct.GetList((int)id, 0, (int)brand, eStoreUser.AccountId, search).OrderByDescending(o => o.ProductId).ToArray<Product>();
                }
                else
                {
                    productsModel.RelatedProducts = dbProduct.GetList((int)id, 0, (int)brand, eStoreUser.AccountId, search).OrderBy(o => o.ProductId).ToArray<Product>();
                }
            }
            else if (productsModel.Sort == 4)
            {
                if (productsModel.Order > 1)
                {
                    productsModel.RelatedProducts = dbProduct.GetList((int)id, 0, (int)brand, eStoreUser.AccountId, search).OrderByDescending(o => o.CreatedDate).OrderByDescending(o => o.BillOut).ToArray<Product>();
                }
                else
                {
                    productsModel.RelatedProducts = dbProduct.GetList((int)id, 0, (int)brand, eStoreUser.AccountId, search).OrderBy(o => o.CreatedDate).OrderBy(o => o.BillOut).ToArray<Product>();
                }
            }
            productsModel.SearchCategories = string.Join(",", productsModel.RelatedProducts.Select(p => p.Category).Distinct().ToList());


            if (productsModel.RelatedProducts.Count > 0)
            {
                productsModel.MinPriceTotal = Convert.ToDecimal(productsModel.RelatedProducts.Min(o => o.Price));
                productsModel.MaxPriceTotal = Convert.ToDecimal(productsModel.RelatedProducts.Max(o => o.Price));

            }

            if (Convert.ToString(minPrice) != "" && Convert.ToString(maxPrice) != "" && minPrice >= 0 && maxPrice >= 1)
            {
                if (minPrice == maxPrice)
                    maxPrice++;
                productsModel.RelatedProducts = productsModel.RelatedProducts.Where(o => o.Price <= maxPrice && o.Price >= minPrice).ToArray<Product>();
            }
            int relatedProductCount = productsModel.RelatedProducts.Count();

            productsModel.RelatedItemCount = productsModel.RelatedProducts.Count();
            productsModel.RelatedProducts = productsModel.RelatedProducts.Skip(PageStart).Take(PageEnd).ToArray<Product>();

            if ((int)id > 0)
            {
                Category category = dbCategory.Get((int)id);
                Mapper.MapDomainToViewModel(category, productsModel);

                productsModel.BreadCrumb = dbCategory.GetBreadCrumb((int)id, Parameters.MainCategoryId, Parameters.HomePageCategoryId, eStoreUser.CultureInfo);
            }
            else
            {
                productsModel.BreadCrumb = "";
            }

            return PartialView(productsModel);
        }



        #endregion

        #region GetBrands

        //[Child]
        //public ActionResult GetBrands(int? id)
        //{
        //    BrandsModel brandsModel = new BrandsModel();
        //    if (id.HasValue)
        //    {
        //        brandsModel.CategoryId = (int)id;
        //        brandsModel.Brands = dbProduct.GetBrandList((int)id, 0, "").Where(b => b.ItemCount > 0).ToList<Brand>();

        //        brandsModel.BreadCrumb = "";

        //        //brandsModel.BreadCrumb = dbCategory.GetBreadCrumb((int)id, Parameters.MainCategoryId, eStoreUser.CultureInfo);
        //    }

        //    return PartialView(brandsModel);
        //}

        #endregion
    }
}
